<?php
/**
 * PhpStorm
 * User: zucheng
 * Date: 2019/4/29
 */

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Crypt;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Rap2hpoutre\LaravelLogViewer\LaravelLogViewer;

class LogController extends Controller
{
    protected $request;

    private $log_viewer;

    public function __construct(Request $request)
    {
        $this->log_viewer = new LaravelLogViewer();
        $this->request    = $request;
    }

    /**
     * 文件日志展示
     * @param Request $request
     * @return array|bool|\Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|mixed
     */
    public function index(Request $request)
    {
        $folderFiles = [];
        if ($this->request->input('f')) {
            $this->log_viewer->setFolder(Crypt::decrypt($this->request->input('f')));
            $folderFiles = $this->log_viewer->getFolderFiles(true);
        }
        if ($this->request->input('l')) {
            $this->log_viewer->setFile(Crypt::decrypt($this->request->input('l')));
            $all = $this->log_viewer->all();

            $page = $this->request->input('page');
            $limit = $this->request->input('limit');

            $data = array_slice($all, ($page - 1) * $limit, $limit);

            return $this->table($data, count($all));
        }

        $data = [
            'logs'           => $this->log_viewer->all(),
            'folders'        => $this->log_viewer->getFolders(),
            'current_folder' => $this->log_viewer->getFolderName(),
            'folder_files'   => $folderFiles,
            'files'          => $this->log_viewer->getFiles(true),
            'current_file'   => $this->log_viewer->getFileName(),
            'standardFormat' => true,
        ];

//        if ($this->request->wantsJson()) {
//            return $data;
//        }

        if (is_array($data['logs'])) {
            $firstLog = reset($data['logs']);
            if (!$firstLog['context'] && !$firstLog['level']) {
                $data['standardFormat'] = false;
            }
        }

        return view('admin.log.index', $data);
    }

    /**
     * 文件处理
     * @return bool|mixed
     * @throws \Exception
     */
    public function fileAction()
    {
        if ($this->request->input('f')) {
            $this->log_viewer->setFolder(Crypt::decrypt($this->request->input('f')));
        }

        if ($this->request->input('dl')) {
            // 下载
            return $this->download($this->pathFromInput('dl'));
        } elseif ($this->request->has('clean')) {
            // 清空
            app('files')->put($this->pathFromInput('clean'), '');
            return $this->redirect($this->request->url());
        } elseif ($this->request->has('del')) {
            // 删除
            app('files')->delete($this->pathFromInput('del'));
            return $this->redirect($this->request->url());
        } elseif ($this->request->has('delall')) {
            // 删除所有文件
            $files = ($this->log_viewer->getFolderName())
                ? $this->log_viewer->getFolderFiles(true)
                : $this->log_viewer->getFiles(true);
            foreach ($files as $file) {
                app('files')->delete($this->log_viewer->pathToLogFile($file));
            }
            return $this->redirect($this->request->url());
        }

        return $this->error();
    }

    /**
     * @param string $input_string
     * @return string
     * @throws \Exception
     */
    private function pathFromInput($input_string)
    {
        return $this->log_viewer->pathToLogFile(Crypt::decrypt($this->request->input($input_string)));
    }

    /**
     * @param $to
     * @return mixed
     */
    private function redirect($to)
    {
        if (function_exists('redirect')) {
            return redirect($to);
        }

        return app('redirect')->to($to);
    }

    /**
     * @param string $data
     * @return mixed
     */
    private function download($data)
    {
        if (function_exists('response')) {
            return response()->download($data);
        }

        // For laravel 4.2
        return app('\Illuminate\Support\Facades\Response')->download($data);
    }

}